import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/user'
import defaultSettings from '@/settings'

const request = axios.create({
  baseURL: defaultSettings.isMockData ? '' : import.meta.env.VITE_APP_BASE_API,
  withCredentials: true,
  timeout: 60000
})

// request interceptor
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    // config.headers['Content-Type'] = 'application/json'
    // config.headers['Cookie'] = document.cookie
    if (userStore.currentMall) {
      config.headers['mallid'] = userStore.currentMall
    }
    switch (config.baseURL) {
      case '/api':
        config['baseURL'] = import.meta.env.PROD
          ? import.meta.env['VITE_NODE_ENV']
          : '/api'
        break
      case '/serv':
        config['baseURL'] = import.meta.env.PROD
          ? import.meta.env['VITE_APP_BASE_API_SER']
          : '/serv'
        if (config.method === 'post') {
          config.data = {
            ...(config.data || {}),
            cookie: document.cookie
          }
        }
        break
      case '/pdd':
        config['baseURL'] = import.meta.env.PROD
          ? import.meta.env['VITE_APP_BASE_API_PDD']
          : '/pdd'
        break
      default:
        config['baseURL'] = import.meta.env['VITE_APP_BASE_API']
        break
    }
    return config
  },
  (error) => Promise.reject(error)
)

// response interceptor
request.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.status === 0 || res.success) {
      return res
    } else {
      ElMessage({
        message: res.errorMsg || '服务异常',
        type: 'error',
        duration: 5 * 1000
      })
      console.log('err1>>>', res)
      return Promise.reject(new Error(res.errorMsg || 'Error'))
    }
  },
  (error) => {
    console.log('err>>>' + error) // for debug
    ElMessage({
      message: error.message || error.error_msg || error.errorMsg || '服务异常',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request
